package com.heima.wemedia.interceptor;

import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.WmThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器：从header中获取用户存入当前线程TheardLoad
 */
public class WmTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从requet中获取userId到ThreadLoad中
        String userId = request.getHeader("userId");
        //如果useId不为空
        if(StringUtils.isNoneEmpty(userId)) {
            WmUser wmUser = new WmUser();
            wmUser.setId(Integer.parseInt(userId));
            //使用工具类存入用户对象
            WmThreadLocalUtil.setUser(wmUser);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //为了清除内存，不然会导致内存泄露
        WmThreadLocalUtil.clear();
    }
}


